<template>
    <div class="news-container">
        <template v-for="category in newsList" :key="category.id">
            <div class="category-header" v-if="category.list && Array.isArray(category.list) && category.list.length > 0">
                <h3>{{ category.title }}</h3>
            </div>
            <div v-for="item in category.list" :key="item.id" class="news-content">
                <div class="flex items-center justify-between">
                    <div class="flex items-center">
                        <span class="title-color" :style="{ backgroundColor: getClassColor(item.classReal) }">
                            {{ getClassLabel(item.classReal) }}
                        </span>
                        <slot name="extraContent"></slot>
                        <h4 style="font-weight: bold;">{{ item.abstractReal }}</h4>
                    </div>
                    <div class="flex justify-self-endself-end">
                        <span @click="moveup(category.id, item.id, 'up')" v-if="showArrows" class="mr-2"><img :src="Arrow"
                                alt="箭头"></span>
                        <span @click="movedown(category.id, item.id, 'down')" v-if="showArrows" class="mr-2"><img
                                :src="Arrow" class="rotate-180" alt="箭头"></span>
                    </div>
                </div>
                <div class="content-middle">{{ item.abstractRea }}</div>
                <div class="content-footer flex justify-between">
                    <div class="flex items-center">
                        <img :src="item.coverImage" @error="handleImageError">
                        <span style="margin-right: 15px;">由 {{ item.opPerson }} 添加</span>
                    </div>
                    <div class="flex items-center">
                        <el-button v-if="item.isSelect === 1" type="danger"
                            @click="$emit('remove', item.id)">移除</el-button>
                        <bianji></bianji>
                    </div>
                </div>
            </div>
        </template>
    </div>
</template>
<script setup>
import { ref, watch } from 'vue'
import bianji from '@/components/ClickOnTheEditPage.vue'
import { classModelList } from '@/enums/index'
import Arrow from '@/assets/circle-arrow.svg'
import { orderNews } from '@/api/newsApi'

const props = defineProps({
    dataList: {
        type: Array,
        default: () => []
    },
    showArrows: {
        type: Boolean,
        default: false
    }
})

const emits = defineEmits(['remove', 'refresh'])

const newsList = ref([])

// 初始化数据
newsList.value = props.dataList
console.log(props.dataList)

// 监听props.dataList的变化
watch(() => props.dataList, (newVal) => {
    // 使用深拷贝确保响应式更新
    if (newVal) {
        newsList.value = JSON.parse(JSON.stringify(newVal))
    } else {
        newsList.value = []
    }
}, { immediate: true, deep: true })

const getClassLabel = (classModelValue) => {
    const model = classModelList.find(item => item.value === classModelValue)
    return model ? model.label : '未知类型'
}

const getClassColor = (classModelValue) => {
    const model = classModelList.find(item => item.value === classModelValue)
    return model ? model.color : '#a8a8a8'
}

const moveup = async (catId, itemId, direction) => {
    console.log('moveup', catId, itemId, direction)

    // 找到对应的分类
    const categoryIndex = newsList.value.findIndex(cat => cat.id === catId)
    if (categoryIndex === -1) return

    const category = newsList.value[categoryIndex]
    if (!category.list || category.list.length === 0) return

    // 在分类的列表中找到对应项的索引
    const itemIndex = category.list.findIndex(item => item.id === itemId)
    if (itemIndex <= 0) return // 已经是第一项，无法上移

    // 交换位置
    const temp = category.list[itemIndex]
    category.list[itemIndex] = category.list[itemIndex - 1]
    category.list[itemIndex - 1] = temp

    // 更新数据
    newsList.value[categoryIndex] = { ...category }
    
    // 调用接口更新排序
    try {
        // 准备要发送的数据，包含排序后的列表
        const sortedList = category.list.map((item, index) => ({
            id: item.id,
            orderNews: index + 1 // 设置新的排序值
        }));
        
        // 调用API
        const res = await orderNews(sortedList);
        
        if (res.code === 200) {
            console.log('排序更新成功')
            // 通知父组件刷新数据
            emits('refresh');
        } else {
            console.error('排序更新失败')
        }
    } catch (error) {
        console.error('排序更新出错:', error);
        // 如果保存失败，恢复原来的顺序
        category.list[itemIndex - 1] = category.list[itemIndex];
        category.list[itemIndex] = temp;
        newsList.value[categoryIndex] = { ...category };
    }
    console.log(newsList.value)
}

const movedown = async (catId, itemId, direction) => {
    console.log('movedown', catId, itemId, direction)

    // 找到对应的分类
    const categoryIndex = newsList.value.findIndex(cat => cat.id === catId)
    if (categoryIndex === -1) return

    const category = newsList.value[categoryIndex]
    if (!category.list || category.list.length === 0) return

    // 在分类的列表中找到对应项的索引
    const itemIndex = category.list.findIndex(item => item.id === itemId)
    if (itemIndex === -1 || itemIndex >= category.list.length - 1) return // 已经是最后一项，无法下移

    // 交换位置
    const temp = category.list[itemIndex]
    category.list[itemIndex] = category.list[itemIndex + 1]
    category.list[itemIndex + 1] = temp

    // 更新数据
    newsList.value[categoryIndex] = { ...category }
    
    // 调用接口更新排序
    try {
        // 准备要发送的数据，包含排序后的列表
        const sortedList = category.list.map((item, index) => ({
            id: item.id,
            orderNews: index + 1 // 设置新的排序值
        }));
        
        // 调用API
        const res = await orderNews(sortedList);
        
        if (res.code === 200) {
            console.log('排序更新成功')
            // 通知父组件刷新数据
            emits('refresh');
        } else {
            console.error('排序更新失败')
        }
    } catch (error) {
        console.error('排序更新出错:', error);
        // 如果保存失败，恢复原来的顺序
        category.list[itemIndex + 1] = category.list[itemIndex];
        category.list[itemIndex] = temp;
        newsList.value[categoryIndex] = { ...category };
    }
}

// 处理图片加载错误
const handleImageError = (e) => {
    // 隐藏加载失败的图片
    e.target.style.display = 'none'
}


</script>
<style scoped>
.news-container {
    padding: 20px;
    max-width: 1200px;
    margin: 0 auto;
    height: 100%;
    max-height: 100%;
    overflow-y: auto;
    overflow-x: hidden;
    box-sizing: border-box;
}

/* 自定义滚动条样式 */
.news-container::-webkit-scrollbar {
    width: 6px;
}

.news-container::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 3px;
}

.news-container::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 3px;
}

.news-container::-webkit-scrollbar-thumb:hover {
    background: #a8a8a8;
}

.news-content {
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
    padding: 16px;
    margin-bottom: 16px;
    transition: all 0.3s ease;
    border-left: 4px solid transparent;
    width: 100%;
    box-sizing: border-box;
    word-wrap: break-word;
    word-break: break-word;
}

.category-header {
    margin: 20px 0 10px 0;
    padding-bottom: 8px;
    border-bottom: 1px solid #ebeef5;
}

.category-header h3 {
    margin: 0;
    color: #303133;
    font-size: 18px;
    font-weight: 600;
}

.news-content .flex {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
}

.news-content .items-center {
    align-items: center;
}

.news-content .justify-between {
    justify-content: space-between;
}

.title-color {
    background-color: #409EFF;
    color: #fff;
    border-radius: 4px;
    padding: 4px 10px;
    margin-right: 12px;
    font-size: 12px;
    font-weight: 500;
    letter-spacing: 0.5px;
    display: inline-block;
    flex-shrink: 0;
}

.content-middle {
    margin: 12px 0;
    color: #606266;
    line-height: 1.6;
    font-size: 14px;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    line-clamp: 2;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    width: 100%;
    box-sizing: border-box;
}

.content-footer {
    font-size: 13px;
    color: #909399;
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    width: 100%;
    box-sizing: border-box;
}

.content-footer .flex {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
}

.content-footer img {
    width: 32px;
    height: 32px;
    margin-right: 10px;
    border-radius: 50%;
    object-fit: cover;
    border: 1px solid #ebeef5;
    flex-shrink: 0;
}

.content-footer .el-button {
    padding: 6px 12px;
    flex-shrink: 0;
}

.disabled {
    opacity: 0.5;
    cursor: not-allowed;
    /* 其他禁用相关样式 */
}

/* 响应式调整 */
@media (max-width: 768px) {
    .news-container {
        padding: 10px;
    }

    .news-content {
        padding: 12px;
    }

    .content-footer {
        flex-direction: column;
        align-items: flex-start;
        gap: 10px;
    }

    .content-footer .flex:last-child {
        align-self: flex-end;
    }
}
</style>